﻿using Newtonsoft.Json;

using System.ComponentModel;
using System.Linq;
using System.Reflection;

namespace System
{
    public class AutoEnumConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType.IsEnum;
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (objectType.IsValueType)
            {
                objectType = Nullable.GetUnderlyingType(objectType) ?? objectType;
            }
            var array = objectType.GetFields(BindingFlags.Public | BindingFlags.Static);
            foreach (var fieldInfo in array)
            {
                if (fieldInfo.Name.Equals(existingValue))
                {
                    return fieldInfo.GetValue(null);
                }
                var attr = fieldInfo.GetCustomAttribute<DescriptionAttribute>();
                if (attr != null && attr.Description.Equals(existingValue))
                {
                    return fieldInfo.GetValue(null);
                }
            }
            return array.FirstOrDefault().GetValue(null);
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value == null)
            {
                writer.WriteNull();
                return;
            }
            try
            {
                writer.WriteValue(Utils.EnumUtil.GetDescription((Enum)value));
            }
            catch (Exception)
            {
                writer.WriteValue(value.ToString());
            }
        }
    }
}
